
package com.example.testutil.util.file;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.support.annotation.NonNull;
import android.util.Log;

import com.google.gson.Gson;

public class JsonUtil {

    // {
    // "phone" : ["12345678", "87654321"], // 数组
    // "name" : "yuanzhifei89", // 字符串
    // "age" : 100, // 数值
    // "address" : { "country" : "china", "province" : "jiangsu" }, // 对象
    // "married" : false // 布尔值
    // }
    //在线生成实体类 :http://www.bejson.com/json2javapojo/
    public static JSONObject createJson() {
        
        JSONObject phone = new JSONObject();
        JSONArray pArray = new JSONArray();
        pArray.put(12345678);
        pArray.put(8654321);
        try {
            phone.put("phone", pArray);
            phone.put("name", "raymond");
            phone.put("age", 100);
            JSONObject address = new JSONObject();
            address.put("country", "china");
            address.put("province", "HuBei");
            phone.put("address", address);
            phone.put("married", false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return phone;
    }

    public static String  jsonParse(String json) {
        try {
            JSONObject mObject = new JSONObject(json);
            JSONArray mArray = mObject.optJSONArray("phone");
            StringBuilder mBuilder = new StringBuilder();
            for(int i=0;i<mArray.length();i++) {
                int num = mArray.optInt(i);
                mBuilder.append(num);
            }
            mBuilder.append(mObject.optString("name")).append(mObject.optInt("age"));
            JSONObject mJsonObject = mObject.optJSONObject("address");
            mBuilder.append(mJsonObject.optString("country")).append(mJsonObject.optString("province"))
            .append(mObject.optBoolean("married"));
            
           return mBuilder.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }
    
    public static void parseJsonWithGson(@NonNull String jsondata) {
        Gson mGson = new Gson();
        PersonInfo mInfo = mGson.fromJson(jsondata, PersonInfo.class);
        Log.d("raymond", "-------------------"+mInfo.getName()+mInfo.getAge());
        List<String > mList = mInfo.getMphone();
        for(int i=0;i<mList.size();i++) {
            Log.d("raymond", mList.get(i));
        }
    } 
}
